package com.netty.code.self.resp.groupChar;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * TODO
 * @author wuzz
 * @since 2024/7/11
 */
public class Server {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;


    public Server() {

        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);

            serverSocketChannel.bind(new InetSocketAddress(8888));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        try {
            while (true) {
                int select = selector.select();
                if (select > 0) {
                    // 有事件进来
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()) {
                            // 获取客户端通道，，下面两行代码都可以
//                            SocketChannel channel = (SocketChannel) key.channel();
                            SocketChannel channel = serverSocketChannel.accept();
                            // 设置客户端连接为非阻塞
                            channel.configureBlocking(false);
                            // 关注read事件
                            channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                            System.out.println(channel.getRemoteAddress() + "  上线了");
                        } else if (key.isReadable()) {
                            read(key);
                        }
                    }
                } else {
                    System.out.println("等待连接");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void read(SelectionKey key) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println("from 客户端：" + channel.getRemoteAddress() + "   " + msg);
                // 广播消息
                borcast(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    // 广播消息
    private void borcast(String msg, SocketChannel self) {
        for (SelectionKey key : selector.keys()) {
            Channel channel1 = (Channel) key.channel();
            if (channel1 instanceof SocketChannel && channel1 != self) {
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
                try {
                    ((SocketChannel) key.channel()).write(wrap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.listen();
    }

}
